using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using WebAPI.domain;
using WebAPI.domain.Repository;
using WebAPI.infrastructure.Db;

namespace WebAPI.infrastructure.Repository
{
    public class EfRepository<T> : IRepository<T> where T : BaseEntity
    {
        private readonly SqlDbContext _db;
        private readonly DbSet<T> _table;
        public EfRepository(SqlDbContext db)
        {
            _db = db;
            _table = _db.Set<T>();
        }
        public IQueryable<T> Table
        {
            get
            {
                return _table.AsNoTracking();
                // return _table as IQueryable<T>;
            }
        }

        public T Add(T entity)
        {
            entity.IsActived = true;
            entity.IsDeleted = false;
            entity.CreatedAt = DateTime.Now;
            entity.UpdatedAt = DateTime.Now;
            _table.Add(entity);
            _db.SaveChanges();
            return entity;
        }

        public void Delete(T entity)
        {
            entity.IsDeleted = true;
            entity.UpdatedAt = DateTime.Now;
            _table.Update(entity);
            _db.SaveChanges();
        }

        public T GetById(Guid id)
        {
            var entity = _db.Set<T>().AsQueryable().Where(x => x.Id == id && x.IsDeleted == false).FirstOrDefault();
            return entity;
        }

        public void Update(T entity)
        {
            _table.Update(entity);
            _db.SaveChanges();
        }
    }
}